package com.yimi.yinhepda.views.createPackage_module;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.CreateDepteSelectAdapter;
import com.yimi.yinhepda.base.BaseInitActivity;
import com.yimi.yinhepda.db.dao.BuildPckScanTableDao;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.LineVoTableDao;
import com.yimi.yinhepda.db.dao.UCDeptTableDao;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LineVoTable;
import com.yimi.yinhepda.db.table.UCDeptTable;
import com.yimi.yinhepda.entity.bean.CheckBoxItemEntity;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.views.load_module.LoadUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/4/18 0018.
 * <p>
 * 建包选择目的地页面
 *
 * @author tianjin
 */
public class CreateDeptSelectActivity extends BaseInitActivity implements CommonViewHolder.onItemCommonClickListener, TextWatcher {

    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    @Bind(R.id.RecyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.btn_sure)
    Button mBtnQuery;
    @Bind(R.id.edit_input)
    EditText mEditInput;
    @Bind(R.id.btn_sure_two)
    Button mBtnSureTwo;

    private List<DepartmentTable> mDataList = new ArrayList<>();
    private List<DepartmentTable> mTempDataList = new ArrayList<>();
    private CreateDepteSelectAdapter mAdapter;
    private String mDeptCode;
    private String mDeptName;
    /**
     * 运输方式（1:干线；2支线：；3：整车）
     */
    private String lineType;
    private String toCompanyCode;
    private String toCompanyName;
    /**
     * 所属企业Code
     */
    private String belongCompCode;

    /**
     * 登录网点
     */
    private String currentDept;
    /**
     * 1-离线装车选择网点，2-离线卸车选择网点 ，3-无头件选择网点，4-问题件责任部门选择网点
     */
    private int inputType;
    private int operateType;
    List<LineVoTable> lineList = new ArrayList<>();

    @Override
    public String getPageName() {
        return getString(R.string.page_dept_select);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_create_dept_select;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTvTitle.setText(getString(R.string.dept_select_title));
        currentDept = getIntent().getStringExtra("currentDept");
        inputType = getIntent().getIntExtra("inputType", 0);
        operateType = getIntent().getIntExtra("operateType", 0);
    }

    @Override
    public void initEvent() {
        mBtnQuery.setOnClickListener(this);
        mBtnSureTwo.setOnClickListener(this);
        mEditInput.addTextChangedListener(this);
    }

    @Override
    public void initData() {
        showPgDlg("正在加载数据...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                DepartmentTableDao mDepartmentTableDao = new DepartmentTableDao();
                LineVoTableDao mLineVoTableDao = new LineVoTableDao();
                List<String> deptCodes = new ArrayList<>();
                try {
                    if (inputType == 0) {
                        mDataList = mDepartmentTableDao.queryDataNotDelete();
                    } else if (inputType == 1) {
                        //离线装车查询网点
                        lineList = mLineVoTableDao.findSourceZoneCode(currentDept);
                        if (!lineList.isEmpty()) {
                            for (LineVoTable lineBean : lineList) {
                                deptCodes.add(lineBean.getDestZoneCode());
                            }
                        }
                    } else if (inputType == 2) {
                        //离线卸车查询网点
                        lineList = mLineVoTableDao.findDestZoneCode(currentDept);
                        if (!lineList.isEmpty()) {
                            for (LineVoTable lineBean : lineList) {
                                deptCodes.add(lineBean.getSourceZoneCode());
                            }
                        }
                    } else if (inputType == 3) {
                        //无头件网点查询
                        mDataList = mDepartmentTableDao.queryDataNotDelete();
                        Iterator<DepartmentTable> it = mDataList.iterator();
                        while (it.hasNext()) {
                            DepartmentTable item = it.next();
                            if (item.getDeptCode().equals("yimidida") && item.getDeptName().equals("壹米滴答供应链")) {
                                //过滤掉yimidida数据
                                it.remove();
                                break;
                            }
                        }
                    } else if (inputType == 4) {
                        //问题件责任部门选择
                        lineList = mLineVoTableDao.findDeptCode(currentDept);
                        if (!lineList.isEmpty()) {
                            for (LineVoTable lineBean : lineList) {
                                deptCodes.add(lineBean.getSourceZoneCode());
                                deptCodes.add(lineBean.getDestZoneCode());
                            }
                        }
                    }
                    if (!deptCodes.isEmpty()) {
                        mDataList = mDepartmentTableDao.queryDataByDeptCodes(deptCodes);
                    }
                    //查询优速网点数据
                    List<UCDeptTable> ucDeptTableList = new UCDeptTableDao().findAll();
                    for (UCDeptTable item : ucDeptTableList) {
                        DepartmentTable departmentTable = new DepartmentTable();
                        departmentTable.setDeptCode(item.getBaseOrgCode());
                        departmentTable.setDeptName(item.getOrgName());
                        mDataList.add(departmentTable);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                if (mDataList.isEmpty()) {
                    showToast("未查询到数据！");
                    return;
                }
                mTempDataList.addAll(mDataList);
                loadUIAdapter();
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
                showToast("加载数据失败！");
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        /** 查询未上传数据*/
        int totalNotUploadNum = new BuildPckScanTableDao().queryNotUploadDataNum();
        mTvNum.setText(totalNotUploadNum + "");
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_sure:
                String searchText = mEditInput.getText().toString();
                List<DepartmentTable> searchDeptList = new ArrayList<>();
                if ("".equals(searchText)) {
                    mDataList.clear();
                    mDataList.addAll(mTempDataList);
                    loadUIAdapter();
                } else {
                    if (!mTempDataList.isEmpty()) {
                        for (DepartmentTable deptBean : mTempDataList) {
                            if (deptBean.getDeptCode() != null && deptBean.getDeptName() != null) {
                                if (deptBean.getDeptCode().contains(searchText) || deptBean.getDeptName().contains(searchText)) {
                                    if (operateType == 1) {
                                        //无头件查询网点，过滤掉大区和小区网点数据（deptType=7 and deptType=8）
                                        if (deptBean.getDeptType() != 7 && deptBean.getDeptType() != 8) {
                                            searchDeptList.add(deptBean);
                                        }
                                    } else {
                                        searchDeptList.add(deptBean);
                                    }
                                }
                            }
                        }
                        if(!searchDeptList.isEmpty()){
                            mDataList.clear();
                            mDataList.addAll(searchDeptList);
                            loadUIAdapter();
                        }else{
                            if (inputType == 1) {
                                //装车，查询下一站
                                querySourceArriveByStation(1, searchText, searchDeptList);
                            } else {
                                //卸车，查询上一站
                                querySourceArriveByStation(2, searchText, searchDeptList);
                            }
                        }
                    } else {
                        if (inputType == 1) {
                            //装车，查询下一站
                            querySourceArriveByStation(1, searchText, searchDeptList);
                        } else {
                            //卸车，查询上一站
                            querySourceArriveByStation(2, searchText, searchDeptList);
                        }
                    }
                    if (searchDeptList.isEmpty() && inputType == 4) {
                        //问题件责任部门查询
                        getAllDept(searchDeptList, searchText);
                    }
                }
                break;
            case R.id.btn_sure_two:
                //确定选择的
                Bundle bundle = new Bundle();
                bundle.putString("deptCode", mDeptCode);
                bundle.putString("deptName", mDeptName);
                bundle.putString("lineType", lineType);
                bundle.putString("toCompany", toCompanyCode);
                bundle.putString("belongCompCode", belongCompCode);
                setResult(RESULT_OK, CreateDeptSelectActivity.this.getIntent().putExtras(bundle));
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 查询上下一站
     */
    private void querySourceArriveByStation(int operType, String searchDept, final List<DepartmentTable> searchDeptList) {
        LoadUtil.querySourceArriveByStation(operType, searchDept, new UICallBack() {
            @Override
            public void onError(String msg) {
                ToastUtil.showToast(msg);
                SoundVibratorManager.playSound(2);
            }

            @Override
            public void onSuccess(Object obj) {
                List<CheckBoxItemEntity> lineList = (List<CheckBoxItemEntity>) obj;
                for (CheckBoxItemEntity item : lineList) {
                    DepartmentTable departmentTable = new DepartmentTable();
                    departmentTable.setDeptCode(item.getCode());
                    departmentTable.setDeptName(item.getName());
                    searchDeptList.add(departmentTable);
                }
                mDataList.clear();
                mDataList.addAll(searchDeptList);
                loadUIAdapter();
            }
        });
    }

    @Override
    public void onItemClickListener(int position) {
        if (position == RecyclerView.NO_POSITION) {
            return;
        }
        DepartmentTable departmentItem = mDataList.get(position);
        for (DepartmentTable entity : mDataList) {
            entity.setCheck(false);
        }
        departmentItem.setCheck(true);

        mDeptCode = departmentItem.getDeptCode();
        mDeptName = departmentItem.getDeptName();
        toCompanyCode = departmentItem.getCompCode();
        belongCompCode = departmentItem.getBelongComp();
        for (int j = 0; j < lineList.size(); j++) {
            if (lineList.get(j).getLineCode().contains(mDeptCode)) {
                lineType = lineList.get(j).getTransportWay();
            }
        }
        mEditInput.setText(mDeptName);

        loadUIAdapter();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    private void getAllDept(final List<DepartmentTable> searchDeptList, final String searchText) {
        showPgDlg("正在加载数据...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                mDataList = new DepartmentTableDao().queryDataNotDelete();
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                if (mDataList.isEmpty()) {
                    showToast("未查询到数据！");
                    return;
                }
                mTempDataList.addAll(mDataList);
                for (DepartmentTable deptBean : mDataList) {
                    if (deptBean.getDeptCode().contains(searchText) || deptBean.getDeptName().contains(searchText)) {
                        searchDeptList.add(deptBean);
                    }
                }
                mDataList.clear();
                mDataList.addAll(searchDeptList);
                loadUIAdapter();
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
                showToast("加载数据失败！");
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if ("".equals(s.toString())) {
            mDataList.clear();
            mDataList.addAll(mTempDataList);
            loadUIAdapter();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void loadUIAdapter() {
        if (mAdapter == null) {
            mAdapter = new CreateDepteSelectAdapter(CreateDeptSelectActivity.this, mDataList, CreateDeptSelectActivity.this);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(CreateDeptSelectActivity.this, LinearLayoutManager.VERTICAL, false));
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }
}
